package com.eonmind.ai.core.draw.schedule;

import com.eonmind.ai.core.draw.schedule.handler.MjSubmitTaskHandler;
import com.eonmind.ai.mapper.AiDrawMapper;
import com.eonmind.ai.mapper.AiDrawPlatformMapper;
import com.eonmind.common.contract.enums.ai.AiArtworkStatusEnum;
import com.eonmind.common.contract.enums.ai.AiDrwaPlatformTypeEnum;
import com.eonmind.common.provider.entity.ai.AiArtwork;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 待提交绘画任务定时提交
 *
 * @author Xujie
 * @since 2025/5/31 21:31
 **/
@Slf4j
@Component
public class DrawTaskSubmitSchedule {
    private static final String submitTaskKey = "sync:draw:submit";

    @Resource
    private AiDrawMapper aiDrawMapper;


    @Resource
    private AiDrawPlatformMapper aiDrawPlatformMapper;

    @Resource
    private MjSubmitTaskHandler mjSubmitTaskHandler;

    @Resource
    private RedissonClient redissonClient;

    @Scheduled(fixedDelay = 1000 * 30)
    public void submitDrawTask() {
        RLock lock = redissonClient.getLock(submitTaskKey);
        boolean flag = lock.tryLock();
        if (!flag) return;
        try {
            List<AiArtwork> aiArtworkList = aiDrawMapper.selectByStatus(AiArtworkStatusEnum.WAIT_SUBMIT.getCode());
            Map<Integer, List<AiArtwork>> taskMap = aiArtworkList.stream()
                    .collect(Collectors.groupingBy(AiArtwork::getPlatformType));
            for (Map.Entry<Integer, List<AiArtwork>> platformTask : taskMap.entrySet()) {
                AiDrwaPlatformTypeEnum platformTypeEnum = AiDrwaPlatformTypeEnum.getByCode(platformTask.getKey());
                if (ObjectUtils.isEmpty(platformTypeEnum)) {
                    log.error("平台类型错误：{}", platformTask.getKey());
                    continue;
                }
                switch (platformTypeEnum) {
                    case MJ -> {
                        mjSubmitTaskHandler.submitTaskList(platformTask.getValue());
                    }
                    default -> {
                        log.error("绘画任务平台错误，提交失败");
                    }
                }
            }
        } catch (Exception e) {
            log.error("MJ定时提交任务异常：{}", e.getMessage(), e);
        } finally {
            lock.unlock();
        }
    }
}
